package com.huaishushu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.huaishushu.common.BaseContext;
import com.huaishushu.common.CustomException;
import com.huaishushu.entity.AddressBook;
import com.huaishushu.mapper.AddressBookMapper;
import com.huaishushu.service.IAddressBookService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 地址管理 服务实现类
 * </p>
 *
 * @author ChiBaoBaoHuaiShuShu
 * @since 2023-05-28
 */
@Service
@Slf4j
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 添加收货地址
     * @param addressBook
     * @return
     */
    @Override
    public void addressBook(AddressBook addressBook) {
        //设置当前用户的id
        addressBook.setUserId(BaseContext.getCurrentId());
        int insert = addressBookMapper.insert(addressBook);
        if (insert <= 0) {
            throw new CustomException("添加新地址失败");
        }
        log.info("用户新增收货地址：{}",addressBook);
    }

    /**
     * 查询当前用户的所有地址
     * @param addressBook
     * @return
     */
    @Override
    public List<AddressBook> list(AddressBook addressBook) {
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        //根据当前的用户id来查询
        lqw.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        lqw.orderByDesc(AddressBook::getUpdateTime);
        List<AddressBook> addressBooks = addressBookMapper.selectList(lqw);
        return addressBooks;
    }

    /**
     * 修改默认地址
     * @param addressBook
     * @return
     */
    @Transactional
    @Override
    public void setDefault(AddressBook addressBook) {
        //获取当前用户id
        addressBook.setUserId(BaseContext.getCurrentId());

        //先将当前用户的其他的地址都设置成不是默认的地址
        LambdaUpdateWrapper<AddressBook> luw = new LambdaUpdateWrapper<>();
        luw.eq(AddressBook::getUserId, addressBook.getUserId());
        luw.set(AddressBook::getIsDefault, 0);
        addressBookMapper.update(null, luw);

        //在将用户选择的当前地址id的地址设置成默认地址
        addressBook.setIsDefault(1);
        addressBookMapper.updateById(addressBook);

    }


}
